package cn.easy.kitchen.service;

import cn.easy.base.bean.PageBean;
import cn.easy.base.service.BaseService;
import cn.easy.kitchen.domain.MaterialBase;
import cn.easy.kitchen.repository.MaterialBaseDao;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Component
public class MaterialBaseService extends BaseService<MaterialBase> {
    @Autowired
    private MaterialBaseDao	materialBaseDao;

    public Page<MaterialBase> search(Map<String, Object> searchParams, PageBean pageBean) {
        return materialBaseDao.findAll(spec(searchParams), pageBean.toPageRequest(new Sort(Direction.DESC, "createdAt")));
    }

    public List<MaterialBase> search(Map<String, Object> searchParams, Sort... sort) {
        return materialBaseDao.findAll(spec(searchParams), sort == null || sort.length == 0  ? new Sort(Direction.DESC, "createdAt") : sort[0]);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void delete(String id) {
        materialBaseDao.delete(id);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteAll() {
        materialBaseDao.deleteAll();
    }

    public MaterialBase getOne(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        return materialBaseDao.findOne(id);
    }

    public MaterialBase findByNo(String no) {
        List<MaterialBase> list = materialBaseDao.findByNo(no);
        return list.isEmpty() ? null : list.get(0);
    }

    public MaterialBase findByOldNo(String oldNo) {
        List<MaterialBase> list = materialBaseDao.findByOldNo(oldNo);
        return list.isEmpty() ? null : list.get(0);
    }

    public List<MaterialBase> findAll(List<String> idList) {
        return Lists.newArrayList(materialBaseDao.findAll(idList));
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public MaterialBase save(MaterialBase materialBase) {
        return materialBaseDao.save(materialBase);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void save(List<MaterialBase> materialBaseList) {
        materialBaseDao.save(materialBaseList);
    }

    /**
     * 统计食材种类
     * @return
     */
    public int countMaterialBase() {
        return materialBaseDao.countMaterial();
    }
}


